<template>
  <div>
    <!-- 标准检验项目表单弹窗 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="1000px"
      draggable
      align-center
      destroy-on-close
      @close="closeDialog"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="120">
        <!-- <p class="p_title">检验项目信息</p> -->
        <!-- <el-row> -->
        <!-- <el-col :span="8">
            <el-form-item label="检验类型" prop="checkTypeId">
              <el-select
                style="width: 100%"
                v-model="formData.checkTypeId"
                placeholder="请选择检验类型"
                filterable
                clearable
                :disabled="props.isReadonly"
                @change="changeEffectCheckType"
              >
                <el-option
                  v-for="item in effectCheckTypeList"
                  :key="item.id"
                  :label="item.checkTypeName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
        <!-- <el-col :span="8">
            <el-form-item label="项目" prop="projectId">
              <el-select
                style="width: 100%"
                v-model="formData.projectId"
                placeholder="请选择项目"
                clearable
                filterable
                :disabled="isBind"
                @change="changeProject"
              >
                <el-option
                  v-for="item in projectList"
                  :key="item.id"
                  :label="item.projectName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
        <!-- <el-col :span="8">
            <el-form-item label="工序" prop="processId">
              <el-select
                style="width: 100%"
                v-model="formData.processId"
                placeholder="请选择工序"
                clearable
                filterable
                :disabled="props.isReadonly"
                @change="changeProcess"
              >
                <el-option
                  v-for="item in processList"
                  :key="item.id"
                  :label="item.processName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品" prop="productId">
              <el-select
                style="width: 100%"
                v-model="formData.productId"
                placeholder="请选择产品"
                :disabled="props.isReadonly"
                filterable
                clearable
                :filter-method="customFilter"
                @change="changeProduct"
              >
                <el-option
                  v-for="item in filteredOptions"
                  :key="item.id"
                  :label="item.materialName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="项目规范码" prop="checkItemId">
              <el-select
                style="width: 100%"
                v-model="formData.checkItemId"
                placeholder="请选择项目规范码"
                :disabled="
                  !formData.productId ||
                  !formData.processId ||
                  !formData.checkTypeId ||
                  props.isReadonly
                "
                clearable
                filterable
                @change="changeProjectRule"
              >
                <el-option
                  v-for="item in produceRuleList"
                  :key="item.id"
                  :label="item.checkItemName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预检单数" prop="preNum">
              <el-input
                v-model="formData.preNum"
                placeholder="请输入预检单数"
                :disabled="props.isReadonly"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="检验项目描述" prop="checkItemRemark">
              <el-input
                type="textarea"
                v-model="formData.checkItemRemark"
                placeholder=""
                rows="1"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-divider content-position="left" border-style="dashed"
          >生产信息</el-divider
        >
        <el-row>
          <el-col :span="8">
            <el-form-item label="计划" prop="planId" labelWidth="70">
              <el-input
                v-model="formData.planCode"
                placeholder="请选择计划"
                clearable
                readonly
                :disabled="props.isReadonly"
                style="width: 100%"
                @click="showWorkOrderSelect"
              >
                <template #append>
                  <el-button type="success" plain @click="showWorkOrderSelect"
                    >选择</el-button
                  >
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="铸件号">
              <el-input
                v-model="formData.batchCode"
                placeholder=""
                clearable
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="计划数量">
              <el-input
                v-model="formData.planQuantity"
                placeholder=""
                clearable
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        <p class="p_title mb-[10px]">检验规则</p> -->
        <el-descriptions class="margin-top w-full" title="" :column="3" border>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">检验类型</div>
            </template>
            <div style="width: 100%; word-break: break-all">
              {{ formData.qmsCheckItemDTO?.checkTypeName || "" }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">工序</div>
            </template>
            <div style="width: 100%; word-break: break-all">
              {{ formData.qmsCheckItemDTO?.processName || "" }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">产品</div>
            </template>
            <div style="width: 100%; word-break: break-all">
              {{ formData.qmsCheckItemDTO?.productName || "" }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item :span="2">
            <template #label>
              <div class="cell-item">项目规范码</div>
            </template>
            <div style="width: 100%; word-break: break-all">
              {{ formData.qmsCheckItemDTO?.checkItemName || "" }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item :span="1">
            <template #label>
              <div class="cell-item">预检单数</div>
            </template>
            <div style="width: 100%; word-break: break-all">
              {{ formData?.preNum ?? "" }}
            </div>
          </el-descriptions-item>
          <el-descriptions-item :span="3">
            <template #label>
              <div class="cell-item">检验项目描述</div>
            </template>
            <div style="width: 100%; word-break: break-all">
              {{ formData.qmsCheckItemDTO?.checkItemRemark || "" }}
            </div>
          </el-descriptions-item>
        </el-descriptions>
        <p class="p_title mt-[15px] mb-[10px]">检验项</p>
        <el-table
          ref="dataTableRef"
          :data="sopItemList"
          highlight-current-row
          border
          max-height="350px"
          class="sopItemList"
        >
          <el-table-column
            label="作业项名称"
            prop="sopItemName"
            min-width="100"
            align="center"
          >
            <template #default="{ $index, row }">
              <span v-if="row.sopItem.sopExecute == '1'" class="c-red">* </span>
              <span>{{ row.sopItemName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="检测值"
            prop="standardValue"
            min-width="140"
            align="center"
            show-overflow-tooltip
          >
            <template #default="{ $index, row }">
              <el-form-item label-width="0">
                <el-input
                  v-if="row.sopItem.standardValue == 1"
                  v-model="row.sopItemValue"
                  placeholder="请输入"
                  clearable
                  @change="changeStandardInput(row, $index)"
                />
                <el-select
                  v-if="row.sopItem.standardValue == 2"
                  style="width: 100%"
                  v-model="row.sopItemValueId"
                  placeholder="请选择"
                  clearable
                  @change="changeStandardSelect(row, $index)"
                >
                  <el-option
                    v-for="item in row.sopItem.details"
                    :key="item.id"
                    :label="item.standardValue"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="检测结果"
            prop="sopItemResult"
            min-width="60"
            align="center"
          >
            <template #default="{ $index, row }">
              <el-tag v-if="row.sopItemResult === 1" type="success"
                >合格</el-tag
              >
              <el-tag v-if="row.sopItemResult === 0" type="danger"
                >不合格</el-tag
              >
              <el-tag v-if="row.sopItemResult === '1'" type="success"
                >合格</el-tag
              >
              <el-tag v-if="row.sopItemResult === '0'" type="danger"
                >不合格</el-tag
              >
            </template>
          </el-table-column>

          <el-table-column
            label="上限值"
            prop="standardMaxValue"
            min-width="50"
            align="right"
          >
            <template #default="{ $index, row }">
              <span>{{ row.sopItem.standardMaxValue }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="下限值"
            prop="standardMinValue"
            min-width="50"
            align="right"
          >
            <template #default="{ $index, row }">
              <span>{{ row.sopItem.standardMinValue }}</span>
            </template>
          </el-table-column>

          <!-- <el-table-column
            label="上限值"
            prop="standardMaxValue"
            min-width="50"
            align="right"
            show-overflow-tooltip
          />
          <el-table-column
            label="下限值"
            prop="standardMinValue"
            min-width="50"
            align="right"
            show-overflow-tooltip
          /> -->
          <el-table-column
            label="附件"
            prop="images"
            min-width="90"
            show-overflow-tooltip
          >
            <template #default="{ $index, row }">
              <div style="overflow: hidden">
                <img
                  v-for="(item, index) in row.sopItem.images"
                  :key="index"
                  :src="`${upPreviewUrl}${item.url}`"
                  style="
                    width: 40px;
                    height: 40px;
                    margin-right: 8px;
                    margin-bottom: 2px;
                    padding: 0px;
                    cursor: pointer;
                    float: left;
                  "
                  @click="
                    handlePictureCardPreview(`${upPreviewUrl}${item.url}`)
                  "
                  alt=""
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="上传"
            prop="uploadImage"
            min-width="120"
            show-overflow-tooltip
          >
            <template #default="{ $index, row }">
              <div style="display: flex; flex-wrap: wrap">
                <CommonUploadFile
                  :files="row.uploadImage"
                  title=""
                  :showText="false"
                  @update-files="(val) => updateFormFiles(val, row)"
                  folderName="qms/qmscheckpre"
                />
                <!-- <span v-for="(item, index) in row.images" :key="index">
                  <img
                    :src="`${upPreviewUrl}${item.url}`"
                    style="
                      width: 30px;
                      height: 30px;
                      margin-right: 10px;
                      cursor: pointer;
                    "
                    @click="
                      handlePictureCardPreview(`${upPreviewUrl}${item.url}`)
                    "
                    alt=""
                  />
                </span> -->
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button type="primary" :loading="loading" @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <SelectMesPlan
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :brekList="brekList"
      formStatus="2"
      :materialCode="formData.productCode"
      :materialName="formData.productName"
      :materialId="formData.productId"
      :processType="formData.processType"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable";
import _ from "lodash-es";
import { deepClone } from "@/utils/commonHooks";
import { checkCommon } from "@/views/qms/checkHook/checkCommon"; // 引入
import { validateNumberCanNot1 } from "@/utils/commonHooks";
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQMSCHECKITEMADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
const isBind = ref(false);

const uploadApi = import.meta.env.VITE_APP_BASE_API;
// 预览url前缀
const upPreviewUrl = `${uploadApi}/system/fileCenter/preview/`;
const handlePictureCardPreview = (url: string) => {
  url = url?.replace("fileCenter/download/", "fileCenter/preview/");
  window.open(url);
};
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  sopType: {
    type: String,
    default: "",
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal === true) {
      // getProjectList();
      // getProcessList();
      // getProductList();
      // getEffectType();
    }
    setTimeout(() => {
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    }, 50);
  }
);

const rules = reactive({
  projectId: [
    { required: true, message: "请选择项目", trigger: ["blur", "change"] },
  ],
  processId: [
    { required: true, message: "请选择工序", trigger: ["blur", "change"] },
  ],
  checkItemId: [
    {
      required: true,
      message: "请输入项目规范码",
      trigger: ["blur", "change"],
    },
    {
      min: 1,
      max: 50,
      message: "长度在 1 到 50 个字符",
      trigger: ["blur", "change"],
    },
  ],
  checkTypeId: [
    { required: true, message: "请选择检验类型", trigger: ["blur", "change"] },
  ],
  preNum: [
    { required: true, message: "请填写预检单数量", trigger: ["blur"] },
    {
      validator: validateNumberCanNot1,
      trigger: "blur",
    },
  ],
  productId: [
    { required: true, message: "请选择产品", trigger: ["blur", "change"] },
  ],
  planId: [
    { required: true, message: "请选择计划", trigger: ["blur", "change"] },
  ],
  enabled: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  standardId: "",
  standardCode: "",
  standardName: "",
  productId: "",
  effectTypeCode: "",
  checkTypeId: "",
  checkRuleId: "",
  checkTypeName: "",
  projectId: "",
  projectCode: "",
  projectName: "",
  processId: "",
  processCode: "",
  processName: "",
  productCode: "",
  productName: "",
  checkItemCode: "",
  checkItemId: "",
  checkItemName: "",
  checkItemRemark: "",
  opeTypeCode: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  batchCode: "",
  planQuantity: "",
  preNum: "",
  planCode: "",
  planId: "",
  ruleCode: "",
  ruleName: "",
  checkNum: "",
  checkFrequency: "",
  weekNum: "",
  qmsPointCheckOrderDTO: {},
});

const { changeOpeType, getEffectTypeCode, effectTypeCodeList } = checkCommon(
  ref(formData)
);
watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, newVal);
      console.log("formData", formData);
      sopItemList.value = formData.qmsPointCheckOrderDTO.details || [];
    }
  }
);

async function getProduceRuleListEdit() {
  const { data } = await request({
    url: "/qms/qmscheckitem/getList",
    method: "post",
    data: {
      // projectCode: formData.projectCode,
      processCode: formData.processCode,
      productCode: formData.productCode,
      effectCheckTypeId: formData.checkTypeId,
    },
  });
  produceRuleList.value = data;
}

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.standardId = "";
  formData.standardCode = "";
  formData.standardName = "";
  formData.effectTypeCode = "";
  formData.checkTypeId = "";
  formData.checkTypeName = "";
  formData.projectId = "";
  formData.projectCode = "";
  formData.projectName = "";
  formData.processId = "";
  formData.processCode = "";
  formData.processName = "";
  formData.productId = "";
  formData.productCode = "";
  formData.productName = "";
  formData.checkItemCode = "";
  formData.checkItemId = "";
  formData.checkItemName = "";
  formData.checkItemRemark = "";
  formData.opeTypeCode = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.batchCode = "";
  formData.planQuantity = "";
  formData.checkRuleId = "";
  effectTypeCodeList.value = [];
  // effectCheckTypeList.value = [];
  processList.value = [];
  standardList.value = [];
  sopItemList.value = [];
  isBind.value = false;

  formData.preNum = "";
  formData.planCode = "";
  formData.planId = "";
  formData.ruleCode = "";
  formData.ruleName = "";
  formData.checkNum = "";
  formData.checkFrequency = "";
  formData.weekNum = "";
  formData.qmsPointCheckOrderDTO = {};
}

const loading = ref(false);

/** 标准检验项目保存提交 */
function handleSubmit() {
  console.log("sopItemList.value", sopItemList.value);
  // 判断测量值是否是数字
  for (let j = 0; j < sopItemList.value.length; j++) {
    if (sopItemList.value[j]?.sopItem?.standardValue == "1") {
      if (isNaN(Number(sopItemList.value[j]?.sopItemValue))) {
        ElMessage.error(
          `${sopItemList.value[j].sopItemName}的检测值只能为数字`
        );
        return false;
      }
    }
  }

  // 判断是否为空
  for (let j = 0; j < sopItemList.value.length; j++) {
    if (sopItemList.value[j]?.sopItem?.sopExecute == "1") {
      if (!sopItemList.value[j]?.sopItemValue) {
        ElMessage.error(`${sopItemList.value[j].sopItemName}的检测值不能为空`);
        return false;
      }
    }
  }

  // 计算是否合格
  // const listCheckOrder: any = taskInfo.value.listCheckOrder;
  let passStatus = 1;
  for (let i = 0; i < sopItemList.value.length; i++) {
    if (
      sopItemList.value[i]?.sopItemValue &&
      sopItemList.value[i].sopItemResult == "0"
    ) {
      passStatus = 0;
    }
  }

  formData.passStatus = passStatus;
  formData.qmsPointCheckOrderDTO.details = sopItemList.value;

  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      // const params = {
      //   batchCode: formData.batchCode || "",
      //   checkItemId: formData.checkItemId || "",
      //   checkRuleId: formData.checkRuleId || "",
      //   checkTypeId: formData.checkTypeId || "",
      //   effectTypeCode: formData.effectTypeCode || "",
      //   opeTypeCode: formData.opeTypeCode || "",
      //   planId: formData.planId || "",
      //   preNum: formData.preNum || "",
      //   processCode: formData.processCode || "",
      //   productCode: formData.productCode || "",
      //   productId: formData.productId || "",
      //   productName: formData.productName || "",
      //   ruleName: formData.ruleName || "",
      //   standardId: formData.standardId || "",
      // };

      console.log("formData", formData);
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/qmscheckdoc/handleSave",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

const changeOperateType = (val) => {
  formData.checkTypeId = "";
  // effectCheckTypeList.value = [];
  // changeOpeType(val);
};
const projectList = ref([]);

const getProjectList = async () => {
  const { data } = await request({
    url: "/mdm/mdmprojectinfo/getList",
    method: "post",
    data: {},
  });
  projectList.value = data;
};

const processList = ref([]);

const getProcessList = async () => {
  const { data } = await request({
    url: "/mes/mesprocess/getList",
    method: "post",
    data: {},
  });
  processList.value = data;
};

const productList = ref([]);

const getProductList = async () => {
  const { data } = await request({
    url: "/mdm/mdmmaterial/getList",
    method: "post",
    data: {
      materialType: "3",
    },
  });
  productList.value = data;
  filteredOptions.value = deepClone(productList.value);
};
// 产品型号列表选择赋值
const filteredOptions = ref<any>([]);
const customFilter = _.debounce((query: any) => {
  if (!query) {
    filteredOptions.value = [...productList.value];
    return;
  }
  filteredOptions.value = productList.value.filter((option: any) =>
    option.materialName?.toLowerCase().includes(query.toLowerCase())
  );
}, 300);

const produceRuleList = ref([]);

const getProduceRuleList = async () => {
  if (
    // formData.projectCode &&
    formData.processCode &&
    formData.productCode &&
    formData.checkTypeId
  ) {
    const { data } = await request({
      url: "/qms/qmscheckitem/getList",
      method: "post",
      data: {
        // projectCode: formData.projectCode,
        processCode: formData.processCode,
        productCode: formData.productCode,
        effectCheckTypeId: formData.checkTypeId,
      },
    });

    if (!data || data.length === 0) {
      produceRuleList.value = [];
      formData.checkItemId = "";
      formData.checkItemCode = "";
      formData.checkItemName = "";
      formData.checkItemRemark = "";
    } else {
      produceRuleList.value = data;
    }
  } else {
    produceRuleList.value = [];
    formData.checkItemCode = "";
    formData.checkItemId = "";
    formData.checkItemName = "";
    formData.checkItemRemark = "";
  }
};

onMounted(() => {
  // getCheckRuleList();
});
const effectCheckTypeList = ref([]);
const getEffectType = async () => {
  formData.checkTypeId = "";
  const { data } = await request({
    url: "/qms/qmschecktype/getList",
    method: "post",
    data: {},
  });
  effectCheckTypeList.value = data;
};

const standardList = ref([]);
const changeProduct = async (id) => {
  clearPlanInfo();
  if (!id) {
    formData.productCode = "";
    formData.productName = "";
    getProduceRuleList();
    return;
  }
  const current: any = productList.value.find((item: any) => {
    return item.id == id;
  });
  formData.productCode = current.materialCode ?? "";
  formData.productName = current.materialName ?? "";
  getProduceRuleList();
};

const changeEffectCheckType = async (id) => {
  if (!id) {
    getProduceRuleList();
    return;
  }
  const current: any = effectCheckTypeList.value.find((item: any) => {
    return item.id == id;
  });
  getProduceRuleList();
};

const changeProcess = async (id) => {
  clearPlanInfo();
  if (!id) {
    formData.processCode = "";
    formData.processName = "";
    formData.processType = "";
    getProduceRuleList();
    return;
  }
  const current: any = processList.value.find((item: any) => {
    return item.id == id;
  });
  formData.processCode = current.processCode ?? "";
  formData.processName = current.processName ?? "";
  formData.processType = current.processType.toString() ?? "";
  getProduceRuleList();
};

const changeProject = async (id) => {
  if (!id) {
    formData.projectCode = "";
    formData.projectName = "";
    getProduceRuleList();
    return;
  }
  const current: any = projectList.value.find((item: any) => {
    return item.id == id;
  });
  formData.projectCode = current.projectCode ?? "";
  formData.projectName = current.projectName ?? "";
  getProduceRuleList();
};

const changeProjectRule = async (id) => {
  if (!id) {
    formData.checkItemName = "";
    formData.checkItemCode = "";
    formData.checkItemRemark = "";
    formData.opeTypeCode = "";
    formData.effectTypeCode = "";
    formData.standardId = "";
    formData.checkRuleId = "";
    return;
  }
  const current: any = produceRuleList.value.find((item: any) => {
    return item.id == id;
  });
  formData.checkItemName = current.checkItemName ?? "";
  formData.checkItemCode = current.checkItemCode ?? "";
  formData.checkItemRemark = current.checkItemRemark ?? "";
  formData.opeTypeCode = current.opeTypeCode ?? "";
  formData.effectTypeCode = current.effectTypeCode ?? "";
  formData.standardId = current.standardId ?? "";
  formData.checkRuleId = current.effectCheckRuleId ?? "";

  getCheckItem();
  getCheckStandard(current.standardId);
  getCheckRule(current.effectCheckRuleId);
};

const getCheckItem = async () => {
  const { data } = await request({
    url: "/qms/qmscheckitem/get/" + formData.checkItemId,
    method: "get",
    data: {},
  });

  formData.checkItemName = data.checkItemName ?? "";
  formData.checkItemCode = data.checkItemCode ?? "";
  formData.checkItemRemark = data.checkItemRemark ?? "";
  formData.opeTypeCode = data.opeTypeCode ?? "";
  formData.effectTypeCode = data.effectTypeCode ?? "";
  formData.standardId = data.standardId ?? "";
  formData.checkRuleId = data.effectCheckRuleId ?? "";
};

const checkStandardList = ref<any>([]);
const getCheckStandard = async (standardId) => {
  const { data } = await request({
    url: "/qms/qmssopstandard/getSopStandard/" + standardId,
    method: "get",
    data: {},
  });
  // sopItemList.value = data.itemDTOS || [];
};

const getCheckRule = async (effectCheckRuleId) => {
  const { data } = await request({
    url: "/qms/qmscheckrule/get/" + effectCheckRuleId,
    method: "get",
    data: {},
  });
  formData.ruleName = data.ruleName ?? "";
  formData.ruleCode = data.ruleCode ?? "";
  formData.checkNum = data.checkNum ?? "";
  formData.checkFrequency = data.checkFrequency ?? "";
  formData.weekNum = data.weekNum ?? "";
};

const getPlanInfo = async (planId) => {
  const { data } = await request({
    url: "/mes/mesplanworkingform/get/" + planId,
    method: "get",
    data: {},
  });
  formData.planCode = data.processingOrderNumber ?? "";
  formData.batchCode = data.plannedBatch ?? "";
  formData.planQuantity = data.planQuantity ?? "";
};
const sopItemList = ref([]);

//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    formData.planId = data.id;
    formData.planCode = data.processingOrderNumber;
    formData.batchCode = data.plannedBatch;
    formData.planQuantity = data.planQuantity;
  }
};
const clearPlanInfo = () => {
  formData.planId = "";
  formData.planCode = "";
  formData.batchCode = "";
  formData.planQuantity = "";
};
// 回显的数据
const brekList = ref([]);
const showWorkOrderSelect = () => {
  if (props.isReadonly) {
    return;
  }
  if (!formData.processId || !formData.productId) {
    ElMessage.error("请先选择工序和产品");
    return;
  }
  selectDialogSELECT.value.visible = true;
};

// input 检测值
function changeStandardInput(row, index) {
  if (row.sopItemValue === "") {
    row.sopItemResult = "";
    return;
  }
  if (!row.sopItem.standardMinValue && !row.sopItem.standardMaxValue) {
    row.sopItemResult = "";
    return;
  }
  if (isNaN(Number(row.sopItemValue))) {
    row.sopItemResult = 0;
    return;
  }
  if (
    row.sopItem.standardMinValue === row.sopItem.standardMaxValue &&
    Number(row.sopItemValue) != Number(row.sopItem.standardMinValue)
  ) {
    row.sopItemResult = 0;
    return;
  }
  if (
    row.sopItem.standardMinValue != row.sopItem.standardMaxValue &&
    Number(row.sopItemValue) < Number(row.sopItem.standardMinValue)
  ) {
    row.sopItemResult = 0;
    return;
  }
  if (
    row.sopItem.standardMinValue != row.sopItemstandardMaxValue &&
    Number(row.sopItemValue) > Number(row.sopItem.standardMaxValue)
  ) {
    row.sopItemResult = 0;
    return;
  }
  row.sopItemResult = 1;
}

// select 检测值
function changeStandardSelect(row, index) {
  const current = row.sopItem.details.find(
    (item) => item.id == row.sopItemValueId
  );
  if (current) {
    row.sopItemValue = current.standardValue;
    row.sopItemResult = current.resultValue == 1 ? 1 : 0;
  } else {
    row.sopItemResult = "";
  }
}

function updateFormFiles(val, row) {
  row.uploadImage = val;
}
</script>
<style lang="scss" scoped>
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 120px !important;
}
.p_title {
  font-size: 14px;
  color: #000;
}
:deep(.el-dialog__body) {
  padding: 20px;
  max-height: calc(100vh - 200px);
  overflow-y: auto;
}
:deep(.sopItemList .el-table__body-wrapper .el-table__cell) {
  padding: 0;
  .el-form-item--default {
    margin-top: 12px;
    margin-bottom: 12px;
  }
}
:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 40px;
  height: 40px;
  // margin-right: 10px;
}
:deep(.file_name) {
  display: none;
}

:deep(.el-upload--picture-card) {
  border-radius: 2px;
  --el-upload-picture-card-size: 40px !important;
  i {
    font-size: 20px;
  }
}
:deep(.el-upload-list__item) {
  margin: 0 8px 3px 0 !important;
}
:deep(.el-upload-list__item-actions) {
  i {
    font-size: 16px !important;
    color: #fff;
  }
}
:deep(.el-upload-list--picture-card .el-upload-list__item-actions span + span) {
  margin-left: 5px !important;
}
</style>
